package cmdb

import (
	"github.com/gin-gonic/gin"
	"k8s-platform/service/cmdb"
	"net/http"
)

var Hostssh hostssh

type hostssh struct{}

// 新增
func (*hostssh) Createssh(c *gin.Context) {
	p := new(struct {
		User         string `form:"user"`
		Password     string `form:"password"`
		Ip           string `form:"ip"`   //连接IP地址
		Post         string `form:"post"` //连接端口
		Command      string `form:"command"`
		CredentialID int64  `form:"credentialID"`
		HostGroupID  int64  `form:"hostgroupID"`
	})

	if err := c.ShouldBindJSON(p); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90400,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	hostmain, err := cmdb.Hostssh.Createssh(p.User, p.Password, p.Ip, p.Post, p.Command, p.CredentialID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	hostmain.Ssh_ip = p.Ip
	hostmain.Ssh_port = p.Post
	if err := cmdb.HostServer.Add(hostmain, p.HostGroupID, p.CredentialID); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "添加host主机成功",
		"data": hostmain,
	})
}

// 同步数据
func (*hostssh) Sync(c *gin.Context) {
	sync := new(struct {
		Serverid     int64  `form:"serverid"`
		User         string `form:"user"`
		Password     string `form:"password"`
		Ip           string `json:"ssh_ip"`   //连接IP地址
		Post         string `json:"ssh_post"` //连接端口
		Command      string `form:"command"`
		CredentialID int64  `form:"credentialID"`
	})

	if err := c.ShouldBindJSON(sync); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90400,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	hostmain, err := cmdb.Hostssh.Createssh(sync.User, sync.Password, sync.Ip, sync.Post, sync.Command, sync.CredentialID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	hostmain.ID = sync.Serverid
	if err := cmdb.HostServer.Sync(hostmain, hostmain.ID); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "同步hostserver组成功",
		"data": nil,
	})
}
